import const
import pymongo
from utils import file_util
# mongo_url = 'mongodb://nado:Asd17677142578@192.168.61.14:27017/imgs'
from gridfs import GridFS
mongo_url = None

def get_mongo_url():
    selection = 'mongodb'
    user = const.CFG.get(selection, 'user')
    pwd = const.CFG.get(selection, 'pwd')
    host = const.CFG.get(selection, 'host')
    port = const.CFG.get(selection, 'port')
    db = const.CFG.get(selection, 'db')
    return 'mongodb://{}:{}@{}:{}/{}'.format(user, pwd, host, port, db)


def get_mongo_client():
    '''
    get the MongoDB client
    :return:
    '''
    return pymongo.MongoClient(get_mongo_url())

def upload_file(file_path, file_name, fs_name):
    '''
    upload file to MongoDB
    :param file_path:
    :param file_name:
    :param fs_name:
    :return:
    '''
    client = get_mongo_client()
    db = client['imgs']
    gridFS = GridFS(db, collection=fs_name)
    with open(file_path, 'rb') as f:
        data = f.read()
        gridFS.put(data, filename=file_name)
    client.close()

def get_file_list(filename, bucket_name):
    '''
    get the file list in MongoDB
    :param filename:
    :param bucket_name:
    :return:
    '''
    client = get_mongo_client()
    db = client['imgs']
    gridFS = GridFS(db, collection=bucket_name)
    file_list = gridFS.find({'filename': filename})
    return client, gridFS, file_list

def del_record(query, colle_name):
    client = get_mongo_client()
    db = client['imgs']
    colle = db[colle_name]
    colle.delete_many(query)
    client.close()

def del_file(query, bucket_name):
    client = get_mongo_client()
    db = client['imgs']
    gridFS = GridFS(db, collection=bucket_name)
    file_list = gridFS.find(query)
    for file in file_list:
        gridFS.delete(file._file['_id'])
    client.close()

def insert_many(params, colle_name):
    client = get_mongo_client()
    db = client['imgs']
    colle = db[colle_name]
    for param in params:
        colle.insert_one(param)
    client.close()

def find_file(filename, bucket_name):
    client = get_mongo_client()
    db = client['imgs']
    gridFS = GridFS(db, collection=bucket_name)
    file = gridFS.find_one({'filename': filename})
    return client, file

def find_one(query, colle_name):
    client = get_mongo_client()
    db = client['imgs']
    colle = db[colle_name]
    res = colle.find_one(query)
    client.close()
    return res


